/*
 * @Author: Mainul Islam
 */

package edu.uta.cse.randomgraph.util;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class DirUtil {

	public static int getLastFileNameIndexInDirectory(String dir) {
		int ind = 0;
		
		File folder = new File(dir);
		if( !(folder.exists() || folder.isDirectory()) )
			return ind;
		
	    File[] listOfFiles = folder.listFiles();
		if(listOfFiles == null)
			return ind;
		
		int num;
		List<Integer> fileNameIndex = new ArrayList<Integer>();

	    for (int i = 0; i < listOfFiles.length; i++) {
	    	if (listOfFiles[i].isFile()) {
	    		String str = listOfFiles[i].getName();
	    		str = str.substring(0, str.indexOf('.'));
	    		try {num = Integer.parseInt(str);}
	    	    catch (NumberFormatException e) {num = 0;}
	    	    fileNameIndex.add(num);
	    	} 
	    }
	    
	    if(fileNameIndex.size() <= 0)
	    	return ind;
	    
	    Collections.sort(fileNameIndex);
	    ind = fileNameIndex.get(fileNameIndex.size()-1);
		return ind;
	}
}
